import os
from os import path

from flask import Blueprint, request

from apps import Response

BASE_DIR = path.join(path.dirname(path.abspath(__file__)), r'..\..\logs')
log = Blueprint('log', __name__)


@log.route('/file_list')
def get_log_file_list():
    if not path.exists(BASE_DIR):
        return Response.success({'fileList': []})
    file_list = os.listdir(BASE_DIR)
    return Response.success({'fileList': file_list})


@log.route('/read')
def read_log():
    file_name = dict(request.args).get('name')
    file_path = path.join(BASE_DIR, file_name)
    if not path.exists(file_path):
        return Response.error('文件不存在')
    with open(file_path, 'r', encoding='utf-8') as f:
        f.readline()
        content = f.readlines()
    return Response.success({'content': content})
